/**
 * Created by Administrator on 14-4-14.
 */
var express = require('express');
var app = express();
var log = require("../lib/log");
var cfg = require('../config');
var url = require('url');
var db = require('../lib/db.js');
var RUtil = require('./dataformatUtil');

var oauth2=require('nodeweibo/lib/oauth2');//引入oauth2对象
var users=require('nodeweibo/lib/users');
exports.oauth2=function(request, response){


    if(request.query.code=="begin")
    {

        response.redirect(oauth2.authorize("269683878","218.244.146.188/oauth2", request.query.state));//启动认证

        //request.session.state=request.query.state;
    }
    else{
        console.log("state:"+response.state);
        var myurl= url.parse(request.url,true);
        var options_access_token={
            "code": myurl.query.code,
            "client_id":"269683878",
            "client_secret":"84397dd3fd7f21feb2c246f707739bf3",
            "grant_type":"authorization_code",
            "redirect_uri":"218.244.146.188/oauth2"
        };
        var useruid={"uid":"","access_token":""};
        var options_get_token_info={"access_token":"" };

        //获取获取授权(access_token)
        oauth2.access_token(options_access_token,function(data){
            console.log("access_token");
            options_get_token_info.access_token=data.access_token;
            useruid.uid=data.uid;
            useruid.access_token=data.access_token;
            console.log("useruid"+JSON.stringify(useruid));
            console.log(data);


            //授权查询
            oauth2.get_token_info(options_get_token_info,function(data){
                console.log("get_token_info");
                console.log(data);
                //表示认证成功，接下来要记录并重定向页面
                users.show(useruid,function(data){
                    console.log("show");
                    var rurl = new Buffer(request.query.state, 'base64').toString();
                    console.log(rurl);
                    response.redirect(rurl);
                    return;
                });

            });
        });
        response.redirect("404.html");


    }


};
